<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div class="header-content">
          <h1>NEUSOFT  PE体检管理系统</h1>
          <div class="doctor-info">
            <el-icon><User /></el-icon>
            <span>医生：{{docter.realName}}</span>
          </div>
        </div>
      </el-header>
      <el-container class="main-container">
        <el-aside width="320px">
          <div class="search-panel">
            <div class="panel-header">
              <el-icon><User /></el-icon>
              <h4>预约客户信息</h4>
            </div>

            <el-descriptions class="margin-top" :column="1" border>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">预约编号</div>
                </template>
                {{ user.orderId }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">手机号码</div>
                </template>
                {{ user.userId }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">真实姓名</div>
                </template>
                {{ user.realName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">性别</div>
                </template>
                {{ user.sex == 1 ? "男" : "女" }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">套餐类型</div>
                </template>
                {{ user.smName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <div class="cell-item">体检日期</div>
                </template>
                {{ user.orderDate.substring(0, 10) }}
              </el-descriptions-item>
            </el-descriptions>

            <div class="form-buttons">
              <el-button type="primary" @click="toOrdersList">
                <el-icon><Back /></el-icon>
                返回列表
              </el-button>
            </div>
          </div>
        </el-aside>
        <el-main>



          <div class="demo-collapse">
            <el-collapse>

              <el-collapse-item :title="ci.ciName" v-for="(ci, ciIndex) in detailed" :key="ci.ciId">
                <el-row style="color: #888">
                  <el-col :span="12" style="box-sizing: border-box; padding: 6px 10px"
                    v-for="(cidr, cidrIndex) in ci.list" :key="cidr.ciId">
                    <span style="
                      background-color: #ba634e;
                      color: #fff;
                      box-sizing: border-box;
                      padding: 1px 3px;
                      border-radius: 3px;
                      margin-right: 5px;
                    " v-if="cidr.isError == 1">异</span>

                    <span style="margin-right: 5px; vertical-align: top">{{
                      cidr.name
                      }}</span>

                    <el-input style="width: 26%; margin-right: 2px" size="small" :placeholder="cidr.name"
                      :disabled="user.state==3"
                      v-if="cidr.type != 4" v-model="cidr.value"
                      @blur="cidrCheckByBlur(ciIndex, cidrIndex)" />
                    <el-input style="width: 80%" type="textarea" :rows="2" :placeholder="cidr.name"
                      v-model="cidr.value" v-if="cidr.type == 4" />

                    <span style="margin-right: 15px">{{ cidr.unit }}</span>

                    <span v-if="cidr.normalValueString">正常值范围: {{ cidr.normalValueString }}</span>
                  </el-col>
                </el-row>
                <el-button type="primary" style="margin-top: 8px" @click="updateReportData(ciIndex)"
                  v-if="user.state == 2">{{ ci.ciName }}项保存</el-button>
              </el-collapse-item>

              <el-card class="box-card" style="margin-top: 20px">
                <template #header>
                  <div class="card-header">
                    <span>总检结论</span>
                    <span style="margin-left: 600px;"></span>
                    <el-button class="button" type="danger" @click="updateOrdersState" 
                      v-if="user.state == 2">体检套餐总检结果报告归档</el-button>
                      <el-button type="text" size="big" @click="reportAnalyze"
                      v-if="user.state == 3">ai报告简要分析</el-button>
                  </div>
                </template>
                <div>
                  <el-table :data="overallResultArr" style="width: 100%">
                    <el-table-column type="index" label="编号" width="60" />
                    <el-table-column prop="title" label="总检结论项标题" width="180" />
                    <el-table-column prop="content" label="总检结论项内容" />
                    <el-table-column label="操作" width="180">
                      <template #default="scope">
                        <el-button type="text" size="small" @click="givedatatoDialog(scope.row)"
                        v-if="user.state == 2">更新</el-button>
                        <el-button type="text" size="small" @click="removeOverallResult(scope.row)"
                        v-if="user.state == 2">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>

                  <el-form ref="formRef" :model="overallResultForm" style="margin-top: 20px" label-width="120px"
                    v-if="user.state == 2">
                    <el-form-item label="总检结论标题">
                      <el-input :disabled="user.state == 3" v-model="overallResultForm.title" placeholder="总检结论标题"></el-input>
                    </el-form-item>
                    <el-form-item label="总检结论内容">
                      <el-input :disabled="user.state == 3" v-model="overallResultForm.content" :rows="2" type="textarea"
                        placeholder="总检结论内容"></el-input>
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="addOverallResult">添加</el-button>
                      <el-button type="warning" @click="resetOverallResult">清空</el-button>
                    </el-form-item>
                  </el-form>
                </div>
                <div v-if="Ai_word_show==true">
                  <el-footer style="margin-top: 30px; margin-left: 350px;">
                    <span>AI报告分析</span>
                  </el-footer>
                  <el-card shadow="never" style="background-color: #f8f8f8;">
                        <div style="white-space: pre-wrap; line-height: 1.6;">{{ Ai_analyze }}</div>
                  </el-card>
                </div>
              </el-card>

            </el-collapse>

            <el-dialog v-model="dialogFormVisible" title="修改" width="500">
              <el-form :model="lineData">
                <el-form-item label="总检结论标题" :label-width="formLabelWidth">
                  <el-input   v-model="lineData.title" autocomplete="off"/>
                </el-form-item>
                <el-form-item label="总检结论内容" :label-width="formLabelWidth">
                  <el-input  v-model="lineData.content" autocomplete="off" />
                </el-form-item>
              </el-form>
              <template #footer>
                <div class="dialog-footer">
                  <el-button @click="dialogFormVisible = false" >取消</el-button>
                  <el-button type="primary" @click="updateOverallResult(lineData)">
                    提交
                  </el-button>
                </div>
              </template>
            </el-dialog>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import axios from 'axios'
import { getSessionStorage } from '../common'
import { ElMessage } from 'element-plus'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()

    const state = reactive({
      overallResultForm:{
        title: "",
        content: "",
        orderId: ""
      },
      lineData:{
        orId: "",
        title: "",
        content: "",
      },
      overallResultArr:[],
      user: JSON.parse(route.query.user),
      detailed: {},
      detailed_data:{},
      dialogFormVisible: false,
      docter:getSessionStorage("docter"),
      Ai_analyze:"",
      Ai_word_show:false
    })
    loadOrders()
    function loadOrders() {
      console.log(state.user)
      axios.post('/api/checkItemDetailedBySmId', {
          smId:state.user.smId
      })
        .then(function (response) {
          state.detailed = response.data.data
          console.log("detailed:"+state.detailed)
        })
        .catch(function (error) {
          console.log(error);
        })
    }
    loadOrdersData()
    function loadOrdersData(){
      axios.post('/api/getdetaileddata', {
          orderId:state.user.orderId
      })
        .then(function (response) {
          console.log(response.data.data)
          state.detailed_data = response.data.data
          for(let i = 0 ; i < state.detailed_data.length ; i++){
            // console.log(state.detailed_data[i].list.length)
            for(let j = 0; j < state.detailed_data[i].list.length; j++){
              console.log(state.detailed_data[i].list[j].value)
              state.detailed[i].list[j].value = state.detailed_data[i].list[j].value
              state.detailed[i].list[j].isError = state.detailed_data[i].list[j].isError
              state.detailed[i].list[j].cidrId = state.detailed_data[i].list[j].cidrId
            }
          }
        })
        .catch(function (error) {
          console.log(error);
        })
    }

    function updateReportData(CiIndex){
        console.log(state.detailed[CiIndex])
        axios.post('/api/updateReportData',state.detailed[CiIndex])
                .then(function(response){
                    console.log(response)
                    loadOrdersData()
                })
                .catch(function(error){
                    console.log(error)
                })
    }

    loadOverallResultData()
    function loadOverallResultData(){
      state.overallResultForm.orderId = state.user.orderId
      console.log(state.user)
      axios.post('/api/getoverallresult', {
          orderId:state.user.orderId
      })
        .then(function (response) {
          console.log(response.data.data)
          state.overallResultArr = response.data.data
        })
        .catch(function (error) {
          console.log(error);
        })
    }

    function updateOverallResult(){
      console.log(state.lineData)
      axios.post('/api/updateoverallresult',state.lineData)
        .then(function (response) {
          console.log(response.data.data)
          loadOverallResultData()
          state.dialogFormVisible = false
          state.lineData.title = ""
          state.lineData.content = ""
        })
        .catch(function (error) {
          console.log(error);
        })
    }

    function removeOverallResult(overallresult){
      axios.post('/api/deleteoverallresult',overallresult)
        .then(function (response) {
          console.log(response.data.data)
          loadOverallResultData()
        })
        .catch(function (error) {
          console.log(error);
        })
    }

    function givedatatoDialog(overallresult){
        state.dialogFormVisible = true
        console.log(overallresult)
        state.lineData.orId = overallresult.orId
        state.lineData.title = overallresult.title
        state.lineData.content = overallresult.content
    }

    function addOverallResult(){
      if(state.overallResultForm.title =="" || state.overallResultForm.content==" " ){
          ElMessage.error('不能添加空的总检结论标题或内容')
      }else{
        axios.post('/api/addoverallresult',state.overallResultForm)
        .then(function (response) {
          console.log(response.data.data)
          state.overallResultForm.title = ""
          state.overallResultForm.content = ""
          loadOverallResultData()
        })
        .catch(function (error) {
          console.log(error);
        })
      }

    }

    function resetOverallResult(){
        state.overallResultForm.title = ""
        state.overallResultForm.content = ""
    }

    function toOrdersList() {
      router.push({ name: "OrderList" })
    }

    function updateOrdersState(){
        //1.校验体检报告值是否为空
        let hasEmptyValue = false
        for(let i = 0; i < state.detailed.length; i++) {
          for(let j = 0; j < state.detailed[i].list.length; j++) {
            if(!state.detailed[i].list[j].value) {
              hasEmptyValue = true
              ElMessage.error(`${state.detailed[i].ciName}中的${state.detailed[i].list[j].name}未填写`)
              return
            }
          }
        }

        //2.校验总检结论是否为空
        if(state.overallResultArr.length === 0) {
          ElMessage.error('请至少添加一条总检结论')
          return
        }

        // 如果校验通过，更新订单状态
        axios.post('/api/updateordersstate', {
          orderId: state.user.orderId,
          state: 3
        })
          .then(function (response) {
            console.log(response)
            if(response.data.status === 200) {
              ElMessage.success('体检报告归档成功')
              router.push({ name: "OrderList" })
            } else {
              ElMessage.error(response.data.message || '归档失败')
            }
          })
          .catch(function (error) {
            console.log(error)
            ElMessage.error('系统错误，请稍后重试')
          })
      } 

    function reportAnalyze(){
        console.log(state.detailed)
          // 构建报告分析字符串
        let reportText = "体检报告分析：\n\n";
        
        // 遍历每个检查类别
        state.detailed.forEach(ci => {
          reportText += `【${ci.ciName}】\n`;
          
          // 遍历该类别下的每个检查项
          ci.list.forEach(item => {
            const abnormalMark = item.isError == 1 ? "[异常]" : "[正常]";
            reportText += `${item.name}: ${item.value || '未填写'} ${item.unit || ''} `;
            reportText += `(正常范围: ${item.normalValueString || '无'}) ${abnormalMark}\n`;
          });
          
          reportText += "\n"; // 类别间空一行
        });
        console.log(reportText)
        axios.post('/api/ai/kimi', {
                message:reportText
              })
              .then(function(response){
                state.Ai_word_show=true
                console.log(response)
                state.Ai_analyze=response.data
                console.log(state.Ai_analyze)
              })
              .catch(function(error){
                console.log(error)
              })
    }

    function cidrCheckByBlur(){
      
    }

    return {
      ...toRefs(state),
      cidrCheckByBlur,
      toOrdersList,
      loadOrders,
      loadOrdersData,
      updateReportData,
      loadOverallResultData,
      updateOverallResult,
      removeOverallResult,
      addOverallResult,
      givedatatoDialog,
      resetOverallResult,
      updateOrdersState,
      reportAnalyze
    }
  }
}
</script>

<style scoped>
.common-layout {
  height: 100vh;
  background: linear-gradient(135deg, #f6f8fc 0%, #e9f0f7 100%);
}

.el-header {
  background: linear-gradient(to right, #ffffff, #f8faff);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  height: 60px !important;
  border-bottom: 1px solid rgba(64, 158, 255, 0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 100%;
}

.header-content h1 {
  font-size: 22px;
  font-weight: 600;
  background: linear-gradient(120deg, #5e35b1, #7e57c2);

  -webkit-text-fill-color: transparent;
  margin: 0;
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #7e57c2;
  font-size: 14px;
  padding: 8px 16px;
  background: rgba(126, 87, 194, 0.1);
  border-radius: 20px;
}

.doctor-info .el-icon {
  color: #7e57c2;
}

.main-container {
  height: calc(100vh - 60px);
}

.el-aside {
  background: linear-gradient(180deg, #f8f5ff 0%, #f1ebff 100%);
  border-right: 1px solid rgba(126, 87, 194, 0.1);
  padding: 24px;
  width: 320px !important;
  transition: all 0.3s ease;
  box-shadow: 4px 0 16px rgba(0, 0, 0, 0.05);
}

.search-panel {
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(126, 87, 194, 0.08);
  overflow: hidden;
}

.panel-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 24px;
  padding: 16px 20px;
  background: linear-gradient(120deg, #7e57c2, #9575cd);
  color: white;
}

.panel-header h4 {
  font-size: 18px;
  font-weight: 600;
  color: white;
  margin: 0;
}

.panel-header .el-icon {
  font-size: 20px;
  color: white;
}

.margin-top {
  margin-top: 20px;
  padding: 0 20px;
}

.cell-item {
  font-weight: 500;
  color: #606266;
}

.form-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;
  padding: 20px;
  border-top: 1px solid rgba(126, 87, 194, 0.1);
}

.el-button {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
  border-radius: 8px;
}

.el-button--primary {
  background: linear-gradient(135deg, #7e57c2, #673ab7);
  border: none;
}

.el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(126, 87, 194, 0.3);
  background: linear-gradient(135deg, #9575cd, #7e57c2);
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-descriptions__cell) {
  padding: 12px 16px;
}

:deep(.el-descriptions__body) {
  background-color: #ffffff;
}

/* 滚动条美化 */
.el-aside::-webkit-scrollbar {
  width: 6px;
}

.el-aside::-webkit-scrollbar-thumb {
  background: rgba(126, 87, 194, 0.2);
  border-radius: 3px;
}

.el-aside::-webkit-scrollbar-thumb:hover {
  background: rgba(126, 87, 194, 0.4);
}

.el-aside::-webkit-scrollbar-track {
  background: #f5f7fa;
}

/* 添加卡片悬停效果 */
.search-panel:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 24px rgba(126, 87, 194, 0.12);
}
</style>